<template>
  <div v-if="taskOverlay" class="notification-overlay"></div>
</template>
<script>
import { getTaskDetail } from '@/api/common'
import { uniqBy, differenceBy } from 'lodash-es'
import { mapGetters, mapMutations } from 'vuex'
export default {
  data() {
    return {}
  },
  computed: {
    ...mapGetters(['taskOverlay'])
  },
  methods: {
    ...mapMutations(['SET_TASKOVERLAY']),
    toggleTask(data) {
      const _that = this
      const _taskQueuesList = _that.$store.state.app.taskQueuesList
      const _taskVisible = _that.$store.state.app.taskVisible
      const _taskTimes = _that.$store.state.app.taskTimes

      if (!_taskVisible) {
        _that.SET_TASKOVERLAY(true)
        _that.$notification.open({
          key: data.taskId, // 唯一ID,用于更新
          message: data.taskName,
          description: data.remark || '',
          class: 'custom-notification',
          duration: 0,
          icon:
            data.exportStatus === 'FINISHED' ? (
              <a-icon type="check-circle" style="color: #52c41a;" />
            ) : data.exportStatus === 'TASK_FAIL' ? (
              <a-icon type="exclamation-circle" style="color: #faad14;" />
            ) : (
              <a-icon type="loading" style="color: #108ee9;" />
            ),
          onClose: () => {
            _that.SET_TASKOVERLAY(false)
          },
          btn: h => {
            return [
              h(
                'a-button',
                {
                  props: {
                    type: 'default',
                    size: 'small'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  on: {
                    click: () => {
                      _that.SET_TASKOVERLAY(false)
                      _that.$notification.destroy() // 关闭所有
                      _that.$store.dispatch('ToggleTaskVisible', true)
                    }
                  }
                },
                '查看全部任务'
              ),
              h(
                'a-button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled: data.exportStatus === 'PROCESSING' || data.exportStatus === 'CREATED'
                  },
                  style:
                    (data.exportTaskFileList && data.exportTaskFileList.length) ||
                    data.exportStatus === 'PROCESSING' ||
                    data.exportStatus === 'CREATED'
                      ? ''
                      : 'display: none;',
                  on: {
                    click: () => {
                      data.exportTaskFileList.forEach((item, index) => {
                        _that.createIFrame(
                          `${item.fileUrl}?attname=${item.fileName.replace(/[\s"'/\\*?<>:|~%#$&!()]/g, '_')}.xls`,
                          index * 100,
                          1000
                        )
                      })
                      _that.$notification.close(data.taskId)
                      _that.SET_TASKOVERLAY(false)
                    }
                  }
                },
                data.exportStatus === 'PROCESSING' || data.exportStatus === 'CREATED' ? '加载中...' : '下载'
              )
            ]
          }
        })
      }
      if (data.exportStatus === 'PROCESSING' || data.exportStatus === 'CREATED') {
        const _currentData = _taskQueuesList.find(v => v.taskId === data.taskId)
        if (!_currentData) {
          _that.$store.dispatch('SetTaskQueuesList', [..._taskQueuesList, data]) // 加入队列
        }

        if (!_taskTimes) {
          _that.refreshStatus() // 刷新队列状态
        }
      } else {
        if (_taskVisible) {
          // 用于任务列表静默刷新-刷新后再删除
          _that.$store.dispatch('SetTaskQueuesList', uniqBy([data, ..._taskQueuesList], 'taskId'))
        } else {
          // 已加载完成,从队列删除
          _that.$store.dispatch('SetTaskQueuesList', differenceBy(_taskQueuesList, [data], 'taskId'))
        }
        // 导入成功并且在停留在当前页面,强制刷新, 临时方案
        if (data.exportStatus === 'FINISHED' && data.taskType === 'IMPORT' && data.fullPath === this.$route.fullPath) {
          location.reload()
        }
      }
    },

    refreshStatus() {
      const _that = this
      const __taskTimes = setInterval(() => {
        const _taskQueuesList = _that.$store.state.app.taskQueuesList.map(v => v.taskId)
        if (!_taskQueuesList.length) {
          clearInterval(_that.$store.state.app.taskTimes)
          _that.$store.dispatch('SetTaskTimes', undefined)
          return
        }
        getTaskDetail(_taskQueuesList.join(','))
          .then(res => {
            for (let index = 0; index < res.data.length; index++) {
              if (
                _taskQueuesList.includes(res.data[index].taskId) &&
                res.data[index].exportStatus !== 'PROCESSING' &&
                res.data[index].exportStatus !== 'CREATED'
              )
                _that.toggleTask(res.data[index])
            }
          })
          .catch(() => {
            clearInterval(_that.$store.state.app.taskTimes)
            _that.$store.dispatch('SetTaskTimes', undefined)
            _that.$notification.destroy() // 关闭所有
            this.show = false
          })
      }, 2000)

      _that.$store.dispatch('SetTaskTimes', __taskTimes)
    },
    createIFrame(url, triggerDelay, removeDelay) {
      //动态添加iframe，设置src，然后删除
      setTimeout(function() {
        var frame = document.createElement('iframe')
        frame.src = url
        frame.style.display = 'none'
        document.body.appendChild(frame)
        setTimeout(function() {
          frame.remove()
        }, removeDelay)
      }, triggerDelay)
    }
  }
}
</script>

<style lang="less">
.ant-notification {
  left: 50% !important;
  top: 50% !important;
  transform: translate(-50%, -50%);
}
.notification-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); // 半透明黑色
  z-index: 999; // 确保遮罩层在大多数元素之上
}
</style>
